package upload

import (
	"context"
	"gitee.com/bobo-rs/innovideo-services/framework/model"
	"gitee.com/bobo-rs/innovideo-services/framework/model/entity"
	"gitee.com/bobo-rs/innovideo-services/framework/service"
)

// SaveMergeVideoFile 保存合并后的视频文件
func (u *sUpload) SaveMergeVideoFile(ctx context.Context, merge model.UploadBlockGenMerge, item model.UploadBlockFile) error {
	// 处理并保存附件内容
	return u.SaveAttachment(ctx, merge.Hashed, func(ctx context.Context) (*entity.Attachment, error) {
		attach := &entity.Attachment{
			RealName: item.Filename,
			Hasher:   merge.Hashed,
			AttachId: merge.AttachId,
			AttPath:  merge.Url,
			AttUrl:   merge.Url,
		}
		if err := u.extractVideoMetadata(attach); err != nil {
			return nil, err
		}
		return attach, nil
	})
}

// SaveAttachment 保存附件信息
func (u *sUpload) SaveAttachment(ctx context.Context, hashed string, f func(ctx context.Context) (*entity.Attachment, error)) error {
	// 是否已保存[hash值不为空这验证是否已上传]
	if hashed != `` && service.Attachment().CheckAttachmentExistsByHasher(ctx, hashed) {
		return nil
	}
	attach, err := f(ctx)
	if err != nil {
		return err
	}
	// 再次做一次验证
	if hashed == `` && service.Attachment().CheckAttachmentExistsByHasher(ctx, attach.Hasher) {
		return nil
	}
	// 保存数据
	_, err = service.Attachment().SaveAttachment(ctx, *attach)
	return err
}
